import { defineStore } from "pinia";
import { useCookies } from "vue3-cookies";
import axiosHttp from "axios";

export const useStore = defineStore("main", {
  state: () => ({
    status: {
      useable: false,
      pulling: false,
    },
    account: {
      accessToken: "",
      accountProfile: {},
      accountGroup: {},
    },
  }),

  actions: {
    init() {
      return new Promise((resolve, reject) => {

        // Environment
        const { cookies } = useCookies();
        const axios = axiosHttp.create({ validateStatus: () => true });

        // Get information
        const accessToken = cookies.get("access_token");
        if (accessToken) {
          this.status.pulling = true;
          this.account.accessToken = accessToken;

          const userInformation = axios.get("/api/authenticate/profile", {
            headers: { Authorization: "Bearer " + cookies.get("access_token") },
          });
          const groupInformation = axios.get("/api/management/groups", {
            headers: { Authorization: "Bearer " + cookies.get("access_token") },
          });

          axiosHttp.all([userInformation, groupInformation]).then(
            axiosHttp.spread((...responses) => {
              if (responses[0].status === 200) {
                this.account.accountProfile = responses[0].data;
                console.log(
                  "[STATE] Success get user information: ",
                  responses[0]
                );
              } else {
                console.error(
                  "[STATE] Failed get user information: ",
                  responses[0]
                );
                reject(false);
              }

              if (responses[1].status === 200 && responses[1].data["data"] != null) {
                this.account.accountGroup = responses[1].data["data"];
                console.log(
                  "[STATE] Success get user group information: ",
                  responses[1]
                );
              } else {
                console.error(
                  "[STATE] Failed get user group information: ",
                  responses[1]
                );
                reject(false);
              }

              this.status.pulling = false;
              if (responses[0].status === 200 && responses[1].status === 200) {
                this.status.useable = true;
                resolve(true);
              } else {
                resolve(false);
              }
            })
          );
        } else {
          console.log(
            "[STATE] No access token found, skip fetch user information"
          );
          this.status.useable = true;
          resolve(false);
        }
      });
    },
  },
});
